package org.opportunity.api.lucene.toolkit.index;

import java.io.File;
import java.io.IOException;

import javax.management.RuntimeErrorException;

import org.apache.log4j.Logger;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class IndexerTXT extends IndexerManager {
    
    static Logger logger = Logger.getLogger(IndexerTXT.class);

    public IndexerTXT(String indexDir) throws IOException {
	Directory dir = FSDirectory.open(new File(indexDir));
	StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
	IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_36,analyzer);
	config.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
	writer = new IndexWriter(dir, config);
	
    }

    @Override
    public void index(String dataDir) throws IOException {
	if(!ifDirectoryExists(dataDir)) {
	    String message = "The directory " + dataDir + " does not exists";
	    logger.error(message);
	    throw new RuntimeException(message);
	    
	}
	File[] files = new File(dataDir).listFiles();
	if(files.length == 0) {
	    String message = "The directory " + dataDir + " contains no files";
	    logger.error(message);
	    throw new RuntimeException(message);
	}
	for (File file : files) {
	    addFiles(file, Indexer.TXT);
	}
	for (File f : queue) {
	    indexFile(f);

	}
	writer.commit();
	writer.close();
	queue.clear();
	
    }

}
